export const BASE_URL = '/dms'  // 使用代理配置
//前后端分离
//

const request = {
  get(url, data) {
    return new Promise((resolve, reject) => {
      // 处理URL已包含查询参数的情况
      let finalUrl = BASE_URL + url;
      
      // 如果有额外的查询参数
      if (data && data.params) {
        const queryString = Object.entries(data.params)
          .map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
          .join('&');
        
        // 添加查询参数到URL
        finalUrl += (finalUrl.includes('?') ? '&' : '?') + queryString;
      }
      
      console.log('GET请求URL:', finalUrl);
      
      uni.request({
        url: finalUrl,
        method: 'GET',
        header: this.getHeaders(url),
        success: (res) => {
          if (res.statusCode === 401 && !url.includes('/user/login')) {
            // 处理未授权错误，但跳过登录请求
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            reject(new Error('未授权，请重新登录'))
            return
          }
          resolve(res.data)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  post(url, data, config = {}) {
    return new Promise((resolve, reject) => {
      // 设置请求头，登录请求不需要Authorization头
      const headers = {
        'Content-Type': 'application/json'
      }
      
      // 如果不是登录请求，添加认证头
      if (!url.includes('/user/login')) {
        Object.assign(headers, this.getHeaders(url))
      }
      
      // 处理查询参数
      let finalUrl = BASE_URL + url
      if (config && config.params) {
        const queryString = Object.entries(config.params)
          .filter(([_, val]) => val !== undefined)
          .map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
          .join('&')
        
        if (queryString) {
          finalUrl += (finalUrl.includes('?') ? '&' : '?') + queryString
        }
      }
      
      // 打印请求信息
      console.log('Request URL:', finalUrl)
      console.log('Request Method:', 'POST')
      console.log('Request Headers:', headers)
      console.log('Request Data:', data)
      
      uni.request({
        url: finalUrl,
        method: 'POST',
        data: data,
        header: headers,
        success: (res) => {
          // 打印响应信息
          console.log('Response Status:', res.statusCode)
          console.log('Response Headers:', res.header)
          console.log('Response Data:', res.data)

          // 特殊处理登录请求
          if (url.includes('/user/login')) {
            if (res.statusCode === 200) {
              console.log('Login successful')
              resolve(res.data)
              return
            }
            // 登录失败，返回错误信息
            console.error('Login failed:', res.data)
            reject(new Error(res.data.message || '用户名或密码错误'))
            return
          }

          // 处理其他请求的401错误
          if (res.statusCode === 401) {
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            reject(new Error('未授权，请重新登录'))
            return
          }
          
          resolve(res.data)
        },
        fail: (err) => {
          console.error('Request Failed:', err)
          reject(new Error(err.errMsg || '网络请求失败，请检查网络连接'))
        }
      })
    })
  },
  put(url, data) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: BASE_URL + url,
        method: 'PUT',
        data: data,
        header: {
          'Content-Type': 'application/json',
          ...this.getHeaders(url)
        },
        success: (res) => {
          if (res.statusCode === 401) {
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            reject(new Error('未授权，请重新登录'))
            return
          }
          resolve(res.data)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  delete(url, data) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: BASE_URL + url,
        method: 'DELETE',
        data: data,
        header: {
          'Content-Type': 'application/json',
          ...this.getHeaders(url)
        },
        success: (res) => {
          if (res.statusCode === 401) {
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            reject(new Error('未授权，请重新登录'))
            return
          }
          resolve(res.data)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  getHeaders(url) {
    const headers = {
      'Content-Type': 'application/json'
    }
    
    // 如果是登录请求，不添加认证头
    if (url.includes('/user/login')) {
      console.log('Login request, skipping auth header')
      return headers
    }
    
    // 从本地存储获取token
    const token = uni.getStorageSync('token')
    console.log('Current token:', token)
    
    if (token) {
      headers['Authorization'] = `Bearer ${token}`
      console.log('Added auth header:', headers['Authorization'])
    } else {
      console.warn('No token found in storage')
    }
    
    console.log('Final headers:', headers)
    return headers
  },
  // 添加拦截器支持
  interceptors: {
    request: {
      use(callback) {
        this.requestCallback = callback
      }
    },
    response: {
      use(callback) {
        this.responseCallback = callback
      }
    }
  },
  upload: (url, options = {}) => {
    return new Promise((resolve, reject) => {
      const token = uni.getStorageSync('token')
      if (!token) {
        reject(new Error('未登录或token已过期'))
        return
      }

      console.log('Upload URL:', BASE_URL + url)
      console.log('Upload Token:', token)
      console.log('Upload Options:', options)

      uni.uploadFile({
        url: BASE_URL + url,
        ...options,
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          console.log('Upload Response:', res)
          
          if (res.statusCode === 401) {
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            reject(new Error('未授权，请重新登录'))
            return
          }

          try {
            const data = JSON.parse(res.data)
            if (data.code === 200 && data.data) {
              resolve(data.data)
            } else {
              reject(new Error(data.message || '上传失败'))
            }
          } catch (error) {
            console.error('Parse response error:', error)
            reject(new Error('解析响应失败'))
          }
        },
        fail: (error) => {
          console.error('Upload failed:', error)
          reject(error)
        }
      })
    })
  }
}

export default request 